import os
import zipfile
import argparse
import datetime

def log_decompressed_file(zip_path):
    """记录解压日志"""
    log_file = 'decompress_log.txt'
    try:
        with open(log_file, 'a', encoding='utf-8') as f:
            f.write(f"{zip_path}\n")
    except Exception as e:
        print(f"记录解压日志失败: {str(e)}")

def log_error(error_type, path, error_msg):
    """记录错误日志"""
    error_log_file = 'decompress_error.txt'
    try:
        with open(error_log_file, 'a', encoding='utf-8') as f:
            timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            f.write(f"[{timestamp}] {error_type}: {path} - {error_msg}\n")
    except Exception as e:
        print(f"记录解压错误日志失败: {str(e)}")

def decompress_zip(zip_path):
    """解压单个zip文件到同名文件夹"""
    try:
        # 获取zip文件所在目录和基本名称
        base_dir = os.path.dirname(zip_path)
        folder_name = os.path.splitext(os.path.basename(zip_path))[0]
        output_path = os.path.join(base_dir, folder_name)
        
        # 创建目标文件夹
        os.makedirs(output_path, exist_ok=True)
        
        # 解压文件
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(output_path)
        
        # 记录解压日志
        log_decompressed_file(zip_path)
        return output_path
    except PermissionError as e:
        print(f"❌ 解压失败: {zip_path} - 权限不足")
        log_error("权限不足", zip_path, str(e))
        return None
    except Exception as e:
        print(f"❌ 解压失败: {zip_path} - {str(e)}")
        log_error("解压错误", zip_path, str(e))
        return None

def process_zips(directory, max_depth=5, current_depth=0):
    """递归处理目录中的zip文件"""
    if not os.path.isdir(directory):
        return
    
    # 打印当前处理信息
    indent = "  " * current_depth
    print(f"{indent}└── 正在处理第{current_depth}层目录: {directory}")
    
    # 遍历当前目录
    for entry in os.scandir(directory):
        if entry.is_file() and entry.name.lower().endswith('.zip'):
            # 处理zip文件
            zip_path = entry.path
            print(f"{indent}    ├── 发现压缩文件: {entry.name}")
            output_path = decompress_zip(zip_path)
            if output_path:
                print(f"{indent}    └── 解压完成: {output_path}")
                os.remove(zip_path)  # 删除原zip文件
        elif entry.is_dir() and current_depth < max_depth:
            # 递归处理子目录
            try:
                process_zips(entry.path, max_depth, current_depth + 1)
            except PermissionError as e:
                print(f"{indent}⚠️ 权限不足，跳过目录: {entry.path} (错误: {str(e)})")
                log_error("权限不足", entry.path, str(e))
                continue

def main():
    parser = argparse.ArgumentParser(description='文件夹解压工具')
    parser.add_argument('-d', '--directory', default=r"D:\data",
                       help='要处理的目录路径，默认为D:\data')
    parser.add_argument('-m', '--max-depth', type=int, default=3,
                       help='递归处理的最大深度，默认为3')
    args = parser.parse_args()
    
    process_zips(args.directory, max_depth=args.max_depth)

if __name__ == '__main__':
    main()
